/*
 * HSM Proxy Project.
 * Copyright (C) 2013 FedICT.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License version
 * 3.0 as published by the Free Software Foundation.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, see 
 * http://www.gnu.org/licenses/.
 */

package be.fedict.hsm.jca;

import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * HSM Proxy JCA Security Provider.
 * <p/>
 * Usage:
 * 
 * <pre>
 * Security.addProvider(new HSMProxyProvider());
 * </pre>
 * 
 * @author Frank Cornelis
 * 
 */
public class HSMProxyProvider extends Provider {

	private static final long serialVersionUID = 1L;

	public static final String NAME = "HSMProxyProvider";

	public HSMProxyProvider() {
		super(NAME, 1.0, "HSM Proxy Provider");

		putService(new Service(this, "KeyStore", "HSMProxy",
				HSMProxyKeyStore.class.getName(), null, null));

		final Map<String, String> signatureServiceAttributes = new HashMap<String, String>();
		signatureServiceAttributes.put("SupportedKeyClasses",
				HSMProxyPrivateKey.class.getName());
		putService(new HSMProxyProviderService(this, "Signature",
				"SHA1withRSA", HSMProxySignature.class.getName(), null,
				signatureServiceAttributes));
		putService(new HSMProxyProviderService(this, "Signature",
				"SHA256withRSA", HSMProxySignature.class.getName(), null,
				signatureServiceAttributes));
		putService(new HSMProxyProviderService(this, "Signature",
				"SHA512withRSA", HSMProxySignature.class.getName(), null,
				signatureServiceAttributes));
	}

	private static class HSMProxyProviderService extends Service {

		public HSMProxyProviderService(Provider provider, String type,
				String algorithm, String classname, List<String> aliases,
				Map<String, String> attributes) {
			super(provider, type, algorithm, classname, aliases, attributes);
		}

		@Override
		public Object newInstance(Object constructorParameter)
				throws NoSuchAlgorithmException {
			if (super.getType().equals("Signature")) {
				return new HSMProxySignature(this.getAlgorithm());
			}
			return super.newInstance(constructorParameter);
		}
	}
}
